package br.com.pontoclass.primes;

import java.math.BigInteger;
import java.util.Scanner;

import br.com.pontoclass.primes.util.MathLogicUtil;


public  abstract class AbstractPrimesListWriter implements PrimesListWriter {

    protected Scanner scanner;
    protected DestinationList destination;
    private BigInteger base;

    public AbstractPrimesListWriter(Scanner scanner, DestinationList destination, int base) {
        this.scanner = scanner;
        this.destination = destination;
        this.base = new BigInteger(Integer.toString(base));
    }

    @Override
    public void write() {
        BigInteger decimalValue = BigInteger.ZERO; 
        while(scanner.hasNextBigInteger()) {
            BigInteger nextVal = scanner.nextBigInteger();
            while(!decimalValue.equals(nextVal)) {
                destination.addSimple(convertToBase(decimalValue));
                decimalValue = decimalValue.add(BigInteger.ONE);
            }
            destination.addPrime(convertToBase(decimalValue));
            decimalValue = decimalValue.add(BigInteger.ONE);
        }
        destination.finish();
    }

    private BigInteger convertToBase(BigInteger value) {
        return MathLogicUtil.convert(value, base);
    }
}